const os = require('os');
const fs = require('fs');

const os_info = { info: null, arch: null, org: null, type: null, custom: null, pretty_name: null, milestone: null, dist_id: null };
const kyinfoPath = '/etc/.kyinfo';
const osReleasePath = '/etc/os-release';
const kyinfoPathIsExist = fs.existsSync(kyinfoPath);
const osReleasePathIsExist = fs.existsSync(osReleasePath);
//检查系统架构
function getArch() {
  const arch = os.arch();
  let archObj = {
    'x64': 'x86',
    'x86': 'x86',
    'x86_64': 'x86',
    'arm': 'arm',
    'arm64': 'arm',
    'aarch64': 'arm',
    'loongarch': 'loongarch'
  }
  let res = archObj[arch] || arch;
  os_info['arch'] = res;
  return res;
}

function getoskey() {
  let infoKeyList = [os_info['arch'], os_info['org'], os_info['type']];
  let tempInfo = infoKeyList.join('_');
  if (tempInfo == 'x86_openkylin_desktop') {
    os_info['info'] = tempInfo;
  } else {
    os_info['info'] = "undefined";
  }

  return os_info['info'];
}


function parseRelease() {
  let releaseObj = {};
  if (!osReleasePathIsExist) return releaseObj;
  let releaseData = fs.readFileSync(osReleasePath, 'utf8');
  const lines = releaseData.split('\n');

  for (let line of lines) {
    let lineData = line.split('=');
    if (lineData.length != 2) continue;
    releaseObj[lineData[0].toLowerCase()] = lineData[1].toLocaleLowerCase().replace(/"/g, '');
  }
  return releaseObj;
}

function getFileData() {
  //1、架构
  //2、是否是麒麟系统
  //3、是桌面系统还是服务器系统
  //4、是否是V10
  //5、是否带sp，是sp几
  //6、小版本号
  //7、定制版字符
  getArch();
  /*分类型进行处理
  1.存在.kyinfo的系统 ，取值dist_id 中 架构之前的信息
  2.不在.kyinfo的系统，但是存在os-release  的kylin系统
  3.不是kylin的系统，但是存在os-release
  */
  let os_version_id = null;
  if (osReleasePathIsExist) {
    try {
      let releaseInfo = parseRelease();
      if (releaseInfo['pretty_name']) {
        os_info['pretty_name'] = releaseInfo['pretty_name'];
        if (!kyinfoPathIsExist) {
          os_info['pretty_name'] = os_info['pretty_name'].replace(/ /g, "_");
        }
      }
      if (releaseInfo['version_id']) {
        os_version_id = releaseInfo['version_id'];
      }
      if (releaseInfo['version_codename']) {
        os_info['custom'] = releaseInfo['version_codename'];
      }
      if (releaseInfo['id']) {
        os_info['org'] = releaseInfo['id'];
      }
      if (releaseInfo['name']) {
        os_info['org'] = releaseInfo['name'];
      }
      if (os_info['pretty_name'].includes('openkylin')) {
        os_info['type'] = "desktop";
      }


    } catch (err) {
      os_info['info'] = "";
    }
  }
  if (kyinfoPathIsExist && osReleasePathIsExist) {
    os_info['org'] = "kylin";
    try {
      let version_id;
      let data = fs.readFileSync(kyinfoPath, 'utf8');
      // 使用 split 方法将文件内容分割成行数组
      const lines = data.split('\n');
      // 遍历行数组 获取系统架构
      lines.forEach((line) => {
        line = line.replace(/ /g, "");
        if (line.startsWith("milestone=")) {
          os_info['milestone'] = line.slice(10).toLocaleLowerCase();
        } else if (line.startsWith("dist_id=")) {
          os_info['dist_id'] = line.slice(8).toLocaleLowerCase();
        }
      });//end lines
      os_info['type'] = os_info['dist_id'].includes('desktop') ? "desktop" : "server";
      if (os_info['milestone'].indexOf('release')) {
        os_release = os_info['milestone'].slice(os_info['milestone'].indexOf('release') + 8);
      }
      let osCustomList = ['gen'];
      if (os_info['dist_id'].includes('edu')) {
        osCustomList = ['edu'];
      }
      if (os_info['dist_id'].includes('hwe')) {
        osCustomList.push('hwe');
      }
      if (os_info['dist_id'].includes('gfb')) {
        osCustomList.push('gfb')
      }
      os_info['custom'] = osCustomList.join('');
    } catch (err) {
      os_info['info'] = "";
      console.log(err);
    }
  }

}
function getosinfo() {
  getoskey();
  return os_info['info'];
}

function showosinfo() {
  let osData = '';
  let keyList = [];

  if (kyinfoPathIsExist) {
    keyList = ['arch', 'org', 'milestone'];
  }
  else {
    //架构  组织 操作系统类型
    keyList = ['arch', 'org', 'type', 'pretty_name', 'custom'];
  }
  let osDataList = [];
  for (let key of keyList) {
    if (os_info[key]) {
      osDataList.push(os_info[key]);
    }
  }
  osData = osDataList.join('_')
  osData = osData.replace(/^_+|_+$/g, '');
  if (kyinfoPathIsExist) {
    osData = osData.replace("-release-", "-");
    osData = osData.replace(/-/g, "_");
  }
  return osData;
}

function getsupportlist() {
  let strArry = ["X86 openkylin操作系统"];
  return strArry;
}

function getoscontent() {
  return [getosinfo(), showosinfo(), getsupportlist()]
}
getFileData();

module.exports = {
  getosinfo,
  showosinfo,
  getsupportlist,
  getoscontent
}
